package com.zuikaku.nettychat.netty.handler;

import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.zuikaku.nettychat.netty.dto.NettyRequest;
import com.zuikaku.nettychat.netty.framework.ControllerManager;
import com.zuikaku.nettychat.netty.framework.NettyClient;
import com.zuikaku.nettychat.netty.framework.NettyServer;
import com.zuikaku.nettychat.utils.ConvertTools;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

public class MyNettyRequestHandler extends ChannelInboundHandlerAdapter {

    private ControllerManager controllerManager;


    private NettyServer nettyServer;

    public MyNettyRequestHandler(ControllerManager controllerManager, NettyServer nettyServer) {
        this.controllerManager = controllerManager;
        this.nettyServer = nettyServer;
    }

    /**
     * 类样式解码器
     */
    private Schema<NettyRequest> schema = RuntimeSchema.getSchema(NettyRequest.class);

    public void setNettyServer(NettyServer nettyServer) {
        this.nettyServer = nettyServer;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress()+"已加入");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //移除NettyClient
        NettyClient needRemoveClient = nettyServer.getSocketChannelNettyClientMap().get(ctx.channel());
        nettyServer.getOnlineNettyClientList().remove(needRemoveClient);
        nettyServer.getSocketChannelNettyClientMap().remove(ctx.channel());
        System.out.println(ctx.channel().localAddress()+"已离开");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        byte[] bytes = ConvertTools.byteBuffToBytes(msg);
        if(bytes==null||bytes.length==0){
            return;
        }
        //进行转换
        NettyRequest nettyRequest = new NettyRequest();
        ProtobufIOUtil.mergeFrom(bytes,nettyRequest,schema);
        // nettyRequest请求分流与调用
        controllerManager.handleRequest(nettyRequest,(SocketChannel) ctx.channel());
        super.channelRead(ctx, msg);
    }
}
